﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using UniMana.Utils.Configs;

namespace UniMana.Win.Systems
{
    public partial class FrmRestoreDatabase : DevExpress.XtraEditors.XtraForm
    {
        Server m_srv;
        ServerConnection m_serverCon;
        SqlConnection m_sqlCon;
        DataTable m_dtBackupName;
        public FrmRestoreDatabase()
        {
            InitializeComponent();
            m_dtBackupName = new DataTable();
            m_dtBackupName.Columns.Add("BackupDateTime", typeof(DateTime));
            m_dtBackupName.Columns.Add("BackupName", typeof(string));
            Connect();
            LoadBackupFile();
            
        }

        private bool Connect()
        {
            bool bSuccess = false;
            try
            {

                m_sqlCon = new SqlConnection(ServerConfig.ConnectionStringBackup);
                m_sqlCon.Open();
                m_serverCon = new ServerConnection(m_sqlCon);
                m_srv = new Server(m_serverCon);
               
                foreach (Database db in m_srv.Databases)
                {
                    cmbDatabaseList.Properties.Items.Add(db.Name);
                }

                bSuccess = true;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                bSuccess = false;
            }
            return bSuccess;
        }

        private void LoadBackupFile()
        {
            string strSql = "";
            SqlCommand command = m_sqlCon.CreateCommand();
            #region Mở xp_cmdshell
            string strEnableXP_CMDSHELL = "EXEC sp_configure 'show advanced options', 1";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();

            strEnableXP_CMDSHELL = "RECONFIGURE";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();

            strEnableXP_CMDSHELL = "EXEC sp_configure 'xp_cmdshell', 1";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();

            strEnableXP_CMDSHELL = "RECONFIGURE";
            command.CommandText = strEnableXP_CMDSHELL;
            command.ExecuteNonQuery();
            #endregion

            strSql += "Execute xp_CmdShell @Cmd";
            
            command.CommandText = strSql;
            command.Parameters.Add("@Cmd", SqlDbType.NVarChar).Value = @"Dir D:\Database\ *.bak";
            //command.ExecuteNonQuery();
            SqlDataReader nReader = command.ExecuteReader();
            
            while (nReader.Read())
            {
                //nReader.Read();
                string strData = nReader[0].ToString();
                if (strData.Length > 3)
                {
                    if (strData.Substring(strData.Length - 3, 3) == "bak")
                    {
                        DateTime d ;
                        char []c = new [] {' '};
                        string[] temp = strData.Split(c, StringSplitOptions.RemoveEmptyEntries);
                        try
                        {
                             string[]  strdmy = temp[0].Split('/');
                             string date= strdmy[1]+"/"+strdmy[0]+"/"+strdmy[2] +" "+temp[1]+" "+temp[2];
                             d = DateTime.Parse(date);
                            // string strd = strData.Substring(0, 20);
                             string strBackupName = temp[temp.Length - 1];
                             DataRow dr = m_dtBackupName.NewRow();
                             dr["BackupDateTime"] = d;//strd;
                             dr["BackupName"] = strBackupName;
                             m_dtBackupName.Rows.Add(dr);
                        }
                        catch
                        { }
                    }
                }
            }

            nReader.Close();
            command.Dispose();
            m_sqlCon.Close();
            grcDatabaseRestore.DataSource = m_dtBackupName;
        }

        public void ProgressEventHandler(object sender, PercentCompleteEventArgs e)
        {
            this.progressBar1.Value = e.Percent;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Restore res = new Restore();

            this.Cursor = Cursors.WaitCursor;
            try
            {

                string fileName = @"D:\Database\" + grvDatabaseRestore.GetFocusedRowCellValue("BackupName");
                string databaseName = this.cmbDatabaseList.Text;
                res.Database = databaseName;
                res.Action = RestoreActionType.Database;
                res.Devices.AddDevice(fileName, DeviceType.File);

                res.ReplaceDatabase = true;

                this.progressBar1.Value = 0;
                this.progressBar1.Maximum = 100;
                this.progressBar1.Value = 10;

                res.PercentCompleteNotification = 10;
                res.ReplaceDatabase = true;
                res.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);
                res.SqlRestore(m_srv);
                MessageBox.Show("Restore of " + databaseName + " Complete!", "Restore", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            }
            catch (SmoException exSMO)
            {
                MessageBox.Show(exSMO.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
                this.progressBar1.Value = 0;
            }

            //try
            //{

            //    string path = @"D:\Database\" + grvDatabaseRestore.GetFocusedRowCellValue("BackupName");
            //    string strDatabaseName = this.cmbDatabaseList.Text;
            //    string sqlRestore = "Use master Restore Database " + strDatabaseName + " from disk='" + path + "'";
            //    SqlConnection con = new SqlConnection(UniMana.Utils.Config.ServerConfig.ConnectionStringBackup);
            //    con.Open();
            //    SqlCommand cmd = new SqlCommand(sqlRestore, con);
            //    cmd.ExecuteNonQuery();
            //    con.Close();
            //    MessageBox.Show("Database da duoc restore ");

            //}
            //catch (SqlException ex)
            //{
            //    MessageBox.Show(ex.Message, "Restore Database");
            //    return;
            //}
        }

        private void btnDeleteFile_Click(object sender, EventArgs e)
        {
            DialogResult dlgResult = MessageBox.Show("Bạn có chắc xóa bản sao lưu " + grvDatabaseRestore.GetFocusedRowCellValue("BackupName").ToString() + " không ?", "Cảnh báo", MessageBoxButtons.OKCancel);
            if (dlgResult == System.Windows.Forms.DialogResult.OK)
            {
                if (m_dtBackupName.Rows.Count >= 100)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        string strFileName = grvDatabaseRestore.GetFocusedRowCellValue("BackupName").ToString(); //m_dtBackupName.Rows[i][1].ToString();
                        grvDatabaseRestore.DeleteSelectedRows();
                        DeleteFileServer(strFileName);
                    }
                }
            }
        }

        private void DeleteFileServer(string strFileName)
        {
            string strSql = "";
            m_sqlCon.Open();
            strSql += "Execute xp_CmdShell @Cmd";
            SqlCommand command = m_sqlCon.CreateCommand();
            command.CommandText = strSql;
            command.Parameters.Add("@Cmd", SqlDbType.NVarChar).Value = @"Del D:\Database\" + strFileName ;
            command.ExecuteNonQuery();
            m_sqlCon.Close();
        }

       
    }
}